/**
 * 上传图片可拖动切换顺序扩展类
 * wuyang QQ 51594
 * 2023-2-27
 *
 * 调用方式
 * html:
 * <input type="text" lay-skin="mymoveupload" host="http://www.com/images"
 * width=60 height=60 size=300
 * class="layui-hide" name="test_imglist" value="1.jpg,2.jpg,3.jpg"/>
 *js:
 *  layui.use(['myMoveUpload'], function () {
        layui.myMoveUpload.render({});
    });
 *
 *
 * */
layui.define(["jquery", "layer", 'upload'], function (exports) {
    var model_name = "myMoveUpload",
        moveupload_elem = "input[lay-skin='mymoveupload']";

    var $ = layui.jquery, layer = layui.layer, upload = layui.upload;

    var obj = {
        options: {
            elem: moveupload_elem,
            url: 'UploadImages',
            size: 300,
            width: 60,//默认图片宽
            height: 60,//默认图片高
            host: '',
            accept: 'image',//上传类型
            exts: 'jpg|gif|png',
            separator: ','//分隔符
        }
        , render: function (option) {
            var _this = this;
            _this.options = $.extend(_this.options, option);
            _this.style(_this.options.width, _this.options.height);

            $.each($(_this.options.elem), function () {
                    var url = $(this).attr('url') || _this.options.url;
                    var width = $(this).attr('width') || _this.options.width;
                    var height = $(this).attr('height') || _this.options.height;
                    var size = $(this).attr('size') || _this.options.size;
                    var accept = $(this).attr('accept') || _this.options.accept;
                    var exts = $(this).attr('exts') || _this.options.exts;
                    var host = $(this).attr('host') || _this.options.host;
                    _this.options.separator = $(this).attr('separator') || _this.options.separator || ',';

                    var times = new Date().getTime();
                    var btn_id = "imagebtn_" + times;//给上传的加个ID
                    $(this).parent().addClass("mymoveupload-" + times);//加个空css,区分多个上传区域
                    $(this).attr("lay-skin", "mymoveupload");//如果没有定义，强行写入
                    //自定义单上传区的图片大小
                    var styles = '<style>' +
                        '.mymoveupload-' + times + '  .mymoveupload-li img{ width:' + width + 'px; height:' + height + 'px;}' +
                        '.mymoveupload-' + times + '  .mymoveupload-add{width:' + height + 'px; height:' + height + 'px;line-height:' + height + 'px;}' +
                        '</style>';
                    $('head').append(styles);
                    ///////////end////////////////////
                    //////////初始化图片列表//////////////
                    var html_mymoveupload = "<ul class='mymoveupload-ul'>";
                    var save_path = $(this).attr('value').split(_this.options.separator);
                    $.each(save_path, function (key, val) {
                        if (!!val) {
                            html_mymoveupload += '<li class="mymoveupload-li"><img save_path="' + val + '" src="' + host + val + '" alt="">';
                            html_mymoveupload += '<i class="layui-icon layui-icon-close-fill"></i>';
                            html_mymoveupload += '</li>';
                        }
                    });
                    html_mymoveupload += "<li><span class='mymoveupload-add' id=" + btn_id + " >+</span></li>";
                    html_mymoveupload += "</ul>";
                    $(this).after(html_mymoveupload);
                    //////////////////////////////////////////////////
                    var btn = $(this).parent();
                    upload.render({
                        elem: '#' + btn_id, url: url, size: size, accept: accept, exts: exts
                        , multiple: true
                        , done: function (res, index, upload) {
                            if (res.code == 0) {
                                var imglist = $(btn).find(".mymoveupload-add").parent();
                                (imglist.last().before("<li class=\"mymoveupload-li\"><img save_path=\"" + res.object.save_path + "\" src=\"" + res.object.view_path + "\" ><i class=\"layui-icon layui-icon-close-fill\"></i></li>"));
                                $(btn).find("input").first().val(_this.getSavePath(btn));
                                return layer.msg('上传成功');
                            } else {
                                return layer.msg('上传失败');
                            }
                        }
                    });
                    //删除图片，仅前端展示删除了，后台数据库并未删除，这儿可以考虑扩展。
                    btn.find("i").bind('click', function (e) {
                        $(this).parent().remove();
                        $(btn).find("input").first().val(_this.getSavePath(btn));
                    });
                    //拖动开始
                    btn.bind('dragstart', function (e) {
                        btn.dragStartEle = _this.getTarget(e);
                    });
                    //拖动中
                    btn.bind('dragover', function (e) {
                        _this.preventDefault(e);
                    });
                    btn.bind('dragenter', function (e) {
                        _this.preventDefault(e);
                    });
                    //显示删除图标
                    $(".mymoveupload-li").bind("mouseover", function (e) {
                        $(this).find("i").show();
                    });
                    //不显示删除图标
                    $(".mymoveupload-li").bind("mouseout", function (e) {
                        $(this).find("i").hide();
                    });
                    //拖动结束，切换图片
                    btn.bind('drop', function (e) {
                        var eleParent;
                        var target = _this.getTarget(e);
                        _this.preventDefault(e);
                        if (btn.dragStartEle && target) {
                            if (target.nodeName === 'IMG' && btn.dragStartEle.nodeName === 'IMG') {
                                eleParent = btn.dragStartEle.parentNode;
                                target.parentNode.appendChild(btn.dragStartEle);
                                eleParent.appendChild(target);
                                delete btn.dragStartEle;
                                //写入数据至input
                                $(btn).find("input").first().val(_this.getSavePath(btn));
                            }
                        }
                    });
                }
            );
        }
        , getSavePath: function (elem) {//取值
            var savePath = '';
            var _this = this;
            $.each($(elem).find("img"), function (key, val) {
                savePath += ($(val).attr("save_path") + _this.options.separator);
            });
            return savePath;
        }
        , getTarget: function (event) {
            return event.target || event.srcElement;
        }
        , preventDefault: function (event) {
            if (event.preventDefault) {
                event.preventDefault();
            } else {
                event.returnValue = false;
            }
        }
        , style: function (width, height) {
            //默认样式
            var style = '<style>' +
                '.mymoveupload-ul{ list-style:none; }' +
                '.mymoveupload-ul li{position:relative;display:inline; float:left; margin:4px 8px 4px 0px; cursor:pointer }' +
                '.mymoveupload-ul li i{position:absolute;color:#6d4e0d;cursor:pointer;top:-8px;right:-12px;width:20px;height:20px;display:none}' +
                '.mymoveupload-li img{ width:' + width + 'px; height:' + height + 'px; border-radius:5px; }' +
                '.mymoveupload-add{ display:block; padding:0px; margin:0px; width:' + width + 'px; height:' + height + 'px;border-radius:5px; ' +
                'border:1px solid #cccccc; color:#cccccc;line-height:' + height + 'px; text-align:center; font-size:30px }' +
                '</style>';
            $('head').append(style);
        }
    }
    exports(model_name, obj);
});